#ifndef NETWORKCONFIG_H
#define NETWORKCONFIG_H

#include <QObject>
#include <QTcpSocket>
#include <QHostAddress>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTimer>
#include <QMutex>

class NetworkConfig : public QObject
{
    Q_OBJECT
public:
    explicit NetworkConfig(QObject *parent = nullptr);
    ~NetworkConfig();

    // 连接状态枚举
    enum ConnectionState {
        DISCONNECTED,
        CONNECTING,
        CONNECTED,
        RECONNECTING
    };

    // 自定义JSON数据格式结构体
    struct RequestData {
        QString command;      // 操作命令 (e.g. "login", "query_data")
        QJsonObject params;   // 请求参数
        qint64 timestamp;     // 时间戳
    };

    struct ResponseData {
        int status;           // 状态码 (200=成功, 400=错误, 500=服务器错误)
        QString message;      // 状态描述
        QJsonObject data;     // 响应数据
        qint64 timestamp;     // 时间戳
    };

    // 公共接口函数
    void connectToServer(const QString &host, quint16 port);
    void disconnectFromServer();
    void sendRequest(const QString &command, const QJsonObject &params);
    ConnectionState connectionState() const;
    bool isConnected() const;

signals:
    void connected();                        // 连接成功
    void disconnected();                     // 断开连接
    void connectionStateChanged(ConnectionState state); // 连接状态变化
    void responseReceived(const ResponseData &response);  // 收到完整响应
    void errorOccurred(const QString &error);            // 发生错误
    void reconnecting(int attempt);          // 正在尝试重连

private slots:
    void onConnected();
    void onDisconnected();
    void onReadyRead();
    void onErrorOccurred(QAbstractSocket::SocketError socketError);
    void onReconnectTimeout();

private:
    QTcpSocket *tcpSocket;
    QTimer *reconnectTimer;
    QString serverHost;
    quint16 serverPort;
    ConnectionState currentState;
    int reconnectAttempts;
    QMutex sendMutex;

    // 消息缓冲区
    QByteArray receiveBuffer;
    qint32 nextMessageSize = -1;

    // 序列化与反序列化
    QByteArray serializeRequest(const RequestData &request) const;
    ResponseData deserializeResponse(const QByteArray &jsonData) const;
    QByteArray serializeMessage(const QByteArray &data) const;
    void setConnectionState(ConnectionState state);
    void startReconnectTimer();
    void stopReconnectTimer();
    void processBuffer();
};

#endif // NETWORKCONFIG_H
